
//
//  RegistViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/9.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import DynamicBlurView
import Alamofire
import PKHUD
import YYModel
import SwiftyJSON
class RegistViewController: BaseViewController {
    @IBOutlet var thirdButtons: [UIButton]!
    @IBOutlet weak var bgImageView: UIImageView!
    @IBOutlet var borderViews: [UIView]!
    @IBOutlet weak var phoneTextField: UITextField!
    @IBOutlet weak var vcTextField: UITextField!
    @IBOutlet weak var pwTextField: UITextField!
    
    @IBOutlet weak var codeButton: UIButton!
    var timer: Timer?
    var sendCount: Int = 60
    var isRegist = true
    
    var type: String = "0"
    var bindid: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // Do any additional setup after loading the view.
    }
    
    // MARK: 设置UI
    func setUI() {
     
        
        let _ = thirdButtons.map({
            $0.layer.cornerRadius = $0.height / 2
            $0.layer.borderColor = UIColor(hex: 0x86878B).cgColor
            $0.layer.borderWidth = 1
            $0.isHidden = true
        })
        
        let _ = borderViews.map({
            $0.layer.borderColor = UIColor.white.cgColor
            $0.layer.borderWidth = 1
        })
        
        
        pwTextField.attributedPlaceholder = NSAttributedString(string: "请输至少8位数密码", attributes: [NSAttributedStringKey.foregroundColor : UIColor(hex: 0xB6B6B6)])
        vcTextField.attributedPlaceholder = NSAttributedString(string: "请输入验证码", attributes: [NSAttributedStringKey.foregroundColor : UIColor(hex: 0xB6B6B6)])
        
        let blurView = DynamicBlurView(frame: bgImageView.bounds)
        blurView.blurRadius = 10
        view.insertSubview(blurView, aboveSubview: bgImageView)
        var titleText = "注册"
        var phonePlText = "请输入手机号码"
        if !isRegist {
            titleText = "绑定手机号"
            phonePlText = "+86 请输入手机号码"
            for button in thirdButtons {
                button.isHidden = true
            }
        }
        
        titleLabel(text: titleText, nil)
        
        phoneTextField.attributedPlaceholder = NSAttributedString(string: phonePlText, attributes: [NSAttributedStringKey.foregroundColor : UIColor(hex: 0xB6B6B6)])
        
        if UMSocialManager.default().isInstall(UMSocialPlatformType.wechatSession) {
            thirdButtons.last?.isHidden = false
        }
        if UMSocialManager.default().isInstall(UMSocialPlatformType.QQ) {
            thirdButtons[1].isHidden = false
        }
        if UMSocialManager.default().isInstall(UMSocialPlatformType.sina) {
            thirdButtons.first?.isHidden = false
        }
        
    }
    
    override func setNavigation() {
    }
    
    @IBAction func changePwTap(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        pwTextField.isSecureTextEntry = sender.isSelected
    }
    @IBAction func threePartyLoginTaps(_ sender: UIButton) {
        if sender.tag == 0 {
            UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.sina, currentViewController: nil, completion: { (result, error) in
                if (result != nil) {
                    let userInfo = result as! UMSocialUserInfoResponse
                    
                    self.thirdsPartyRedictToOurNet(openid: userInfo.openid, type: "3")
                    
                }else
                {
                    print("--",error.debugDescription)
                }
            })
        }
        else if(sender.tag == 1){
            UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.QQ, currentViewController: nil, completion: { (result, error) in
                if (result != nil) {
                    let userInfo = result as! UMSocialUserInfoResponse
                    self.thirdsPartyRedictToOurNet(openid: userInfo.openid, type: "1")
                }else
                {
                    print("--",error.debugDescription)
                }
            })
        }
        else{
            UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.wechatSession, currentViewController: nil, completion: { (result, error) in
                if (result != nil) {
                    //获取用户的个人信息
                    let userInfo = result as! UMSocialUserInfoResponse
                    print("1111")
                    self.thirdsPartyRedictToOurNet(openid: userInfo.unionId, type: "2")
                    //                    userInfo.uid...
                    //调用本地登录接口
                }else
                {
                    print("--",error.debugDescription)
                }
                
            })
        }
    }
    
    @available(iOS 10.0, *)
    @available(iOS 10.0, *)
    @available(iOS 10.0, *)
    @IBAction func fetchPhoneCode(_ sender: Any) {
        if (phoneTextField.text?.isEmpty)! {
            self.showToast(msg:"手机号码不能为空")
            return
        }
        if !(self.isValidPhone(phone: phoneTextField.text! as NSString)) {
            self.showToast(msg:"手机号码格式不对")
            return
        }
        let requesturl = "\(BaseURL)\(getCodeUrl)"
        let parameter:[String : Any] = ["mp":phoneTextField.text!, "type": "1"]
        self.codeButton.isUserInteractionEnabled = false
        
        Alamofire.request(requesturl, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil).responseJSON { [weak self](response) in
            
            let result = response.result.value as? NSDictionary
            let json = JSON(result!)
            if(response.error == nil){
                
                self?.sendCount = 60
                self?.timer = Timer.scheduledTimer(timeInterval: 1, target: self!, selector: #selector(self?.updateCode), userInfo: nil, repeats: true)
                self?.showToast(msg:json["message"].string!)
                
            }else{
                self?.codeButton.isUserInteractionEnabled = true
                self?.showToast(msg:json["message"].string!)
                print("请求失败\(String(describing: response.error))")
            }
            
        }
    }
    @objc func updateCode() -> Void {
        var enable: Bool = false
        var title: String?
        if self.sendCount > 0 {
            title = "重新发送\(self.sendCount)"
            enable = false
        }else{
            title = "发送验证码"
            enable = true
            if self.timer != nil && (self.timer?.isValid)! {
                self.timer?.invalidate()
            }
            self.timer = nil
            self.sendCount = 60
        }
        self.codeButton.titleLabel?.text = title
        self.codeButton.setTitle(title, for: .normal)
        self.codeButton.isUserInteractionEnabled = enable
        self.sendCount -= 1
    }
    
    @IBAction func enterTap(_ sender: UIButton) {
        if (phoneTextField.text?.isEmpty)! {
            self.showToast(msg:"请输入手机号码")
            return
        }
        if !(self.isValidPhone(phone: phoneTextField.text! as NSString)) {
            self.showToast(msg:"手机号码格式不对")
            return
        }
        if (vcTextField.text?.isEmpty)! {
            self.showToast(msg:"请输入验证码")
            return
        }
        if !(self.isValidPwd(pwd: pwTextField.text! as NSString)) {
            self.showToast(msg:"请输入至少8位数密码")
            return
        }
        
        let requesturl = "\(BaseURL)\(registerUrl)"
        let parameter:[String : Any] = ["mp":phoneTextField.text!,
                         "vcode":vcTextField.text!,
                         "psw":pwTextField.text!,
                         "ac":"IOS",
                         "type":self.type,
                         "bindId": self.bindid]
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter ,
                          encoding: URLEncoding.default,
                          headers: nil).responseJSON {
                            (response) in
            HUD.hide()
            if(response.error == nil){
                
                if let result = response.result.value as? NSDictionary
                {
                    let json = JSON(result)
                    if json["code"].int == 1{
                        self.showToast(msg:"注册成功")
                        let dic = json["data"].dictionary
                        var userModel = UserInfoModel(fromDic: dic!)
                        if let dict = json["data"]["grade"].dictionary {
                            userModel.initGrade(dic: dict)
                        }
                        //注册成功后返回用户信息，需要保存用户信息
                        
                        let mineInfoModel = MineInfoModel.share
                        mineInfoModel.userInfModel = userModel
                        mineInfoModel.token = userModel.token!
                        mineInfoModel.isLogin = true
                        mineInfoModel.saveUserData(userinfo: userModel.toDictionary() as NSDictionary)
                        
                        //注册成功后完善基本信息
                        let essentialInformationVC = EssentialInformationViewController(nibName: "\(EssentialInformationViewController.self)", bundle: nil)
                        self.navigationController?.pushViewController(essentialInformationVC, animated: true)

                    }
                    else{
                        self.showToast(msg:json["message"].string!)
                    }
                }
                

            }else{
                print("请求失败\(String(describing: response.error))")
            }
            
        }
        HUD.show(.label("加载中..."))

    }
    
    
    func thirdsPartyRedictToOurNet(openid: String, type: String) -> Void {
        let requesturl = "\(BaseURL)\(loginUrl)"
        let parameter:[String : Any] = ["bindId":openid,
                                        "type": type]
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter,
                          encoding: URLEncoding.default,
                          headers: nil).responseJSON {
                            (response) in
                            HUD.hide()
                            if(response.error == nil){
                                if let result = response.result.value as? NSDictionary
                                {
                                    
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        
                                        self.showToast(msg:"登录成功")
                                        print("登录成功返回数据\(response.result.value as Any)")
                                        let dic = json["data"].dictionary
                                        var userModel = UserInfoModel(fromDic: dic!)
                                        if let dict = json["data"]["grade"].dictionary {
                                            userModel.initGrade(dic: dict)
                                        }
                                        //注册成功后返回用户信息，需要保存用户信息
                                        
                                        let mineInfoModel = MineInfoModel.share
                                        mineInfoModel.userInfModel = userModel
                                        mineInfoModel.token = userModel.token!
                                        mineInfoModel.isLogin = true
                                        mineInfoModel.saveUserData(userinfo: userModel.toDictionary() as NSDictionary)
                                        mineInfoModel.loadUserData()
                                        
                                        self.navigationController?.popToRootViewController(animated: true)
                                        
                                    }
                                    else{
                                        if json["code"].int == 110 {
                                            self.showToast(msg:json["message"].string!)
                                          
                                        }else{
                                            self.showToast(msg:json["message"].string!)
                                        }
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
  
    @IBAction func pushZC(_ sender: Any) {
        let xyVc = XyViewController(nibName: "\(XyViewController.self)", bundle: nil)
        xyVc.url = "http://www.1du.me/miwebproj/privacy_app.html"
        xyVc.title = "隐私政策"
        self.navigationController?.pushViewController(xyVc, animated: true)
    }
    @IBAction func pushXy(_ sender: Any) {
        let xyVc = XyViewController(nibName: "\(XyViewController.self)", bundle: nil)
        xyVc.url = "http://www.1du.me/miwebproj/agreement_app.html"
        xyVc.title = "注册协议"
        self.navigationController?.pushViewController(xyVc, animated: true)
    }
}
